package com.zjt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjt.bean.User;
import com.zjt.bean.UserExample;
import com.zjt.bean.data.UserData;
import com.zjt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;
    @Override
    public UserData selectUserData(Integer page, Integer limit, String sort, String order,
                                   String username, String mobile) {

        //执行查询之前 👉 使用分页插件 👉 会在执行过程中拼接上sql语句
        PageHelper.startPage(page, limit);
        //username = “test1”  nickname like 测试用户
        //每个service的方法都来创建example对象
        UserExample userExample = new UserExample();

        //排序信息
        userExample.setOrderByClause(sort + " " + order);
        UserExample.Criteria criteria = userExample.createCriteria();
        //criteria.andUsernameEqualTo("test1").andNicknameLike("%测试用户%");
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !"".equals(mobile)) {
            criteria.andMobileLike("%" + mobile + "%");
        }


        List<User> users = userMapper.selectByExample(userExample);

        //int total = users.size();//total并不是我们当前查询出来的结果的数据量 👉 满足条件的总的数据量

        //可以获得分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();

        UserData userData = new UserData();
        userData.setTotal(total);
        userData.setItems(users);

        return userData;
    }
}
